package com.resourcestore.utils;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.resourcestore.utils.CommonUtil;

/**
 * 本拦截器在项目启动时开始运行，主要完成数据字典加载以及权限验证的工作 同时需要完成URL截取的动作
 * 
 * 
 */
public class AuthInterceptor implements Interceptor {

	/**
	 * 
	 */
	protected Logger logger = null;

	private void getLogger() {
		if (null == logger) {
			logger = Logger.getLogger(getClass().getName());
		}
	}

	@Override
	public void destroy() {
	// TODO Auto-generated method stub

	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		getLogger();
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		// 只有在listDatadict为空，或者系统参数中的"是否重载数据字典"为需要重载的状态时才查询数据库
//		if (DatadictDao.listDatadict == null || DatadictDao.listDatadict.size() == 0
//				|| SystemParameter.IS_RELOAD_DATADICT.equals("1")) {
//			DatadictDao datadictDao = new DatadictDao();
//			DatadictDao.listDatadict = datadictDao.listAllDatadict();
//			SystemParameter.IS_RELOAD_DATADICT = "0";
//		}

		// 权限验证暂时未考虑

		// URL截取
		Map session = ActionContext.getContext().getSession();
		
		//验证登录权限
		if(session==null){
			 return "sessionError";
		}
		
		HttpServletRequest request = ServletActionContext.getRequest();
		String queryString = request.getQueryString() == null ? "" : request.getQueryString();
		String sourceURL = request.getRequestURL() + "?" + queryString;// 得目标URL

		String basePath = CommonUtil.urlPortDistinguish(request);
		if (null != session.get("userName")) {

			if (null == sourceURL) {
				return "unknownError";
			}

			// 将得到的URL拆分，去掉前面的部分

			sourceURL = sourceURL.replace(basePath, "");
			if (sourceURL.length() > 400) {
				sourceURL = sourceURL.substring(0, 400);
			}

			if (-1 != queryString.indexOf("intercept=1")) {// 如果url中有intercept=1
				// 的语句，则拦截，如果没有，则不拦截
				// 将得到的URL放入到session中
				CommonUtil.addSourceURLToSession(sourceURL);
			}
			
			
			//将得到的URL放入到数据库中
			//LearnTrackAction learnTrackAction = new LearnTrackAction();
			//learnTrackAction.insertLearnTrack(sourceURL, "");

		} 
		else {
			if (sourceURL.indexOf("login.action") >0 || sourceURL.indexOf("logout.action") >0 || sourceURL.indexOf("rand.action") >0)
				return invocation.invoke();
			else return "sessionError";
		}
		return invocation.invoke();
	}

}
